<template>
  <div class="wrapper">
    <!-- header部分 -->
    <header>
      <p>商家信息</p>
    </header>
    
    <!-- 商家logo部分 -->
    <div class="business-logo">
      <img :src="business.businessImg || defaultBusinessImg" @error="handleImageError">
    </div>
    
    <!-- 商家信息部分 -->
    <div class="business-info">
      <h1>{{business.businessName || '商家名称'}}</h1>
      <p>&#165;{{business.startPrice || 0}}起送 &#165;{{business.deliveryPrice || 0}}配送</p>
      <p>{{business.businessExplain || '暂无商家描述'}}</p>
    </div>
    
    <div class="remark" @click="toRemark">
      <button>评论</button>
    </div>

    <!-- 食品列表部分 -->
    <ul class="food">
      <li v-for="(item,index) in foodArr" :key="item.id">
        <div class="food-left">
          <img :src="item.foodImg || defaultFoodImg" @error="handleFoodImageError">
          <div class="food-left-info">
            <h3>{{item.foodName}}</h3>
            <p>{{item.foodExplain}}</p>
            <p>&#165;{{item.foodPrice}}</p>
          </div>
        </div>
        <div class="food-right">
          <div>
            <i class="fa fa-minus-circle" @click="minus(index)" v-show="item.quantity!=0"></i>
          </div>
          <p><span v-show="item.quantity!=0">{{item.quantity}}</span></p>
          <div>
            <i class="fa fa-plus-circle" @click="add(index)"></i>
          </div>
        </div>
      </li>
    </ul>
    
    <!-- 购物车部分 -->
    <div class="cart">
      <div class="cart-left">
        <div class="cart-left-icon"
          :style="totalQuantity==0?'background-color:#505051;':'background-color:#3190E8;'"
          @click="showCartDetails">
          <i class="fa fa-shopping-cart"></i>
          <div class="cart-left-icon-quantity" v-show="totalQuantity!=0">
            {{totalQuantity}}
          </div>
        </div>
        <div class="cart-left-info">
          <p>&#165;{{totalPrice}}</p>
          <p>另需配送费{{business.deliveryPrice || 0}}元</p>
        </div>
      </div>
      <div class="cart-right">
        <!-- 不够起送费 -->
        <div class="cart-right-item" v-show="totalSettle < (business.startPrice || 0)"
          style="background-color: #535356;cursor: default;">
          &#165;{{business.startPrice || 0}}起送
        </div>
        <!-- 达到起送费 -->
        <div class="cart-right-item" @click="toOrder" v-show="totalSettle >= (business.startPrice || 0)">
          去结算
        </div>
      </div>
    </div>

    <!-- 购物车详情弹窗 -->
    <div v-if="showCartModal" class="cart-modal-overlay" @click="hideCartModal">
      <div class="cart-modal" @click.stop>
        <div class="cart-modal-header">
          <h3>购物车详情</h3>
          <i class="fa fa-times" @click="hideCartModal"></i>
        </div>
        <div class="cart-modal-content">
          <div v-if="cartItems.length === 0" class="empty-cart">
            <p>购物车为空</p>
          </div>
          <ul v-else class="cart-items-list">
            <li v-for="item in cartItems" :key="item.id" class="cart-item">
              <div class="cart-item-info">
                <h4>{{item.food?.foodName || '未知商品'}}</h4>
                <p>&#165;{{item.food?.foodPrice || 0}} × {{item.quantity}}</p>
                <p>小计：&#165;{{(item.food?.foodPrice || 0) * item.quantity}}</p>
              </div>
              <div class="cart-item-actions">
                <button @click="decreaseCartItem(item)" class="btn-decrease">-</button>
                <span class="quantity">{{item.quantity}}</span>
                <button @click="increaseCartItem(item)" class="btn-increase">+</button>
                <button @click="removeCartItem(item)" class="btn-remove">
                  <i class="fa fa-trash"></i>
                </button>
              </div>
            </li>
          </ul>
        </div>
        <div class="cart-modal-footer">
          <div class="cart-actions">
            <button @click="clearCart" class="btn-clear" v-if="cartItems.length > 0">
              清空购物车
            </button>
            <div class="cart-total">
              <p>总计：&#165;{{totalPrice}}</p>
              <p>配送费：&#165;{{business.deliveryPrice || 0}}</p>
              <p class="total-amount">应付：&#165;{{totalSettle}}</p>
            </div>
          </div>
          <button v-if="totalQuantity > 0" @click="toOrder" class="btn-checkout">去结算</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'BusinessInfo',
  data() {
    return {
      businessId: this.$route.query.businessId,
      business: {},
      foodArr: [],
      user: {},
      defaultBusinessImg: require('../assets/default-business.png'),
      defaultFoodImg: require('../assets/default-food.png'),
      cartItems: [],
      showCartModal: false,
      loading: false
    }
  },
  async created() {
    this.user = this.$getSessionStorage('user');
    await this.fetchBusiness();
    await this.fetchFoods();
    
    if (this.user) {
      await this.fetchCart();
    }
  },
  computed: {
    totalPrice() {
      return this.foodArr.reduce((total, item) => total + (item.foodPrice * item.quantity), 0);
    },
    totalQuantity() {
      return this.foodArr.reduce((total, item) => total + item.quantity, 0);
    },
    totalSettle() {
      return this.totalPrice + (this.business.deliveryPrice || 0);
    }
  },
  methods: {
    // 获取商家信息
    async fetchBusiness() {
      try {
        const response = await this.$axios.get(`/api/businesses/${this.businessId}`);
        if (response.data.success) {
          this.business = response.data.data || {};
        } else {
          console.error('获取商家信息失败:', response.data.message);
          this.business = {};
        }
      } catch (error) {
        console.error('获取商家信息失败:', error);
        this.business = {};
      }
    },
    
    // 获取食品列表
    async fetchFoods() {
      try {
        const response = await this.$axios.get('/api/foods', {
          params: {
            business: this.businessId
          }
        });
        
        if (response.data.success) {
          this.foodArr = (response.data.data || []).map(food => ({
            ...food,
            quantity: 0
          }));
        } else {
          console.error('获取食品列表失败:', response.data.message);
          this.foodArr = [];
        }
      } catch (error) {
        console.error('获取食品列表失败:', error);
        this.foodArr = [];
      }
    },
    
    // 获取购物车数据
    async fetchCart() {
      if (!this.user?.userId) return;
      
      try {
        this.loading = true;
        const response = await this.$axios.get('/api/carts', {
          params: {
            userId: this.user.userId
          }
        });
        
        if (response.data.success) {
          this.cartItems = response.data.data || [];
          this.syncCartWithFoods();
        } else {
          console.error('获取购物车失败:', response.data.message);
          this.cartItems = [];
        }
      } catch (error) {
        console.error('获取购物车失败:', error);
        this.cartItems = [];
      } finally {
        this.loading = false;
      }
    },
    
    // 同步购物车数据到食品列表
    syncCartWithFoods() {
      this.foodArr.forEach(food => {
        const cartItem = this.cartItems.find(item => 
          item.food && item.food.id === food.id
        );
        food.quantity = cartItem ? cartItem.quantity : 0;
      });
    },
    
    // 显示购物车详情
    async showCartDetails() {
      if (!this.user) {
        this.$router.push('/login');
        return;
      }
      
      if (this.totalQuantity === 0) {
        alert('购物车为空');
        return;
      }
      
      await this.fetchCart();
      this.showCartModal = true;
    },
    
    // 隐藏购物车弹窗
    hideCartModal() {
      this.showCartModal = false;
    },
    
    // 增加购物车商品数量
    async increaseCartItem(cartItem) {
      try {
        const newQuantity = cartItem.quantity + 1;
        const response = await this.$axios.put(`/api/carts/${cartItem.id}`, {
          quantity: newQuantity
        });
        
        if (response.data.success) {
          await this.fetchCart();
        } else {
          alert('增加数量失败: ' + response.data.message);
        }
      } catch (error) {
        console.error('增加数量失败:', error);
        this.handleCartError(error);
      }
    },
    
    // 减少购物车商品数量
    async decreaseCartItem(cartItem) {
      try {
        const newQuantity = cartItem.quantity - 1;
        if (newQuantity <= 0) {
          await this.removeCartItem(cartItem);
          return;
        }
        
        const response = await this.$axios.put(`/api/carts/${cartItem.id}`, {
          quantity: newQuantity
        });
        
        if (response.data.success) {
          await this.fetchCart();
        } else {
          alert('减少数量失败: ' + response.data.message);
        }
      } catch (error) {
        console.error('减少数量失败:', error);
        this.handleCartError(error);
      }
    },
    
    // 移除购物车商品
    async removeCartItem(cartItem) {
      if (!confirm('确定要移除该商品吗？')) return;
      
      try {
        const response = await this.$axios.delete(`/api/carts/${cartItem.id}`);
        if (response.data.success) {
          await this.fetchCart();
        } else {
          alert('移除商品失败: ' + response.data.message);
        }
      } catch (error) {
        console.error('移除商品失败:', error);
        this.handleCartError(error);
      }
    },
    
    // 清空购物车
    async clearCart() {
      if (!this.user?.userId) {
        this.$router.push('/login');
        return;
      }
      
      if (!confirm('确定要清空购物车吗？')) {
        return;
      }
      
      try {
        this.loading = true;
        const response = await this.$axios.delete('/api/carts', {
          params: {
            userId: this.user.userId
          }
        });
        
        if (response.data.success) {
          this.cartItems = [];
          this.foodArr.forEach(food => {
            food.quantity = 0;
          });
          this.hideCartModal();
          alert('购物车已清空');
        } else {
          alert('清空购物车失败: ' + (response.data.message || '未知错误'));
        }
      } catch (error) {
        console.error('清空购物车失败:', error);
        this.handleCartError(error);
      } finally {
        this.loading = false;
      }
    },
    
    // 统一处理购物车错误
    handleCartError(error) {
      console.error('购物车操作失败:', {
        message: error.message,
        status: error.response?.status,
        data: error.response?.data
      });
      
      if (error.response?.status === 500) {
        alert('服务器内部错误，请稍后再试');
      } else if (error.response?.status === 404) {
        alert('购物车项不存在，请刷新页面');
        this.fetchCart(); // 刷新数据
      } else {
        alert('网络错误，请稍后再试');
      }
    },
    
    toRemark() {
      this.$router.push({
        path: '/remark',
        query: { businessId: this.businessId }
      });
    },
    
    // 添加商品到购物车
    async add(index) {
      if (!this.user) {
        this.$router.push('/login');
        return;
      }
      
      const food = this.foodArr[index];
      if (food.quantity === 0) {
        await this.addToCart(food);
      } else {
        await this.updateCartQuantity(food, food.quantity + 1);
      }
    },
    
    // 减少商品数量
    async minus(index) {
      if (!this.user) {
        this.$router.push('/login');
        return;
      }
      
      const food = this.foodArr[index];
      if (food.quantity > 1) {
        await this.updateCartQuantity(food, food.quantity - 1);
      } else {
        await this.removeFromCart(food);
      }
    },
    
    // 添加商品到购物车
    async addToCart(food) {
      try {
        const cartData = {
          food: {
            id: food.id,
            foodName: food.foodName,
            foodPrice: food.foodPrice,
            foodImg: food.foodImg,
            business: {
              id: this.businessId,
              businessName: this.business.businessName
            }
          },
          customer: {
            id: this.user.userId,
            username: this.user.username
          },
          business: {
            id: this.businessId,
            businessName: this.business.businessName
          },
          quantity: 1
        };
        
        const response = await this.$axios.post('/api/carts', cartData);
        if (response.data.success) {
          await this.fetchCart();
        } else {
          alert('添加到购物车失败: ' + response.data.message);
        }
      } catch (error) {
        console.error('添加到购物车失败:', error);
        this.handleCartError(error);
      }
    },
    
    // 更新购物车商品数量
    async updateCartQuantity(food, newQuantity) {
      try {
        const cartItem = this.cartItems.find(item => 
          item.food && item.food.id === food.id
        );
        
        if (!cartItem) {
          alert('未找到购物车项');
          return;
        }
        
        const response = await this.$axios.put(`/api/carts/${cartItem.id}`, {
          quantity: newQuantity
        });
        
        if (response.data.success) {
          await this.fetchCart();
        } else {
          alert('更新数量失败: ' + response.data.message);
        }
      } catch (error) {
        console.error('更新数量失败:', error);
        this.handleCartError(error);
      }
    },
    
    // 从购物车移除商品
    async removeFromCart(food) {
      try {
        const cartItem = this.cartItems.find(item => 
          item.food && item.food.id === food.id
        );
        
        if (!cartItem) {
          alert('未找到购物车项');
          return;
        }
        
        const response = await this.$axios.delete(`/api/carts/${cartItem.id}`);
        if (response.data.success) {
          await this.fetchCart();
        } else {
          alert('移除商品失败: ' + response.data.message);
        }
      } catch (error) {
        console.error('移除商品失败:', error);
        this.handleCartError(error);
      }
    },
    
    // 跳转到订单页面
    toOrder() {
      if (this.totalQuantity === 0) {
        alert('请先选择商品');
        return;
      }
      
      this.hideCartModal();
      this.$router.push({
        path: '/Orders',
        query: { businessId: this.businessId }
      });
    },
    
    handleImageError(e) {
      e.target.src = this.defaultBusinessImg;
    },
    
    handleFoodImageError(e) {
      e.target.src = this.defaultFoodImg;
    }
  }
}
</script>

<style scoped>
/****************** 总容器 ******************/
.wrapper {
  width: 100%;
  height: 100%;
}

/****************** header部分 ******************/
.wrapper header {
  width: 100%;
  height: 12vw;
  background-color: #0097FF;
  color: #fff;
  font-size: 4.8vw;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 1000;
  display: flex;
  justify-content: center;
  align-items: center;
}

/****************** 商家logo部分 ******************/
.wrapper .business-logo {
  width: 100%;
  height: 35vw;
  margin-top: 12vw;
  display: flex;
  justify-content: center;
  align-items: center;
}

.wrapper .business-logo img {
  width: 40vw;
  height: 30vw;
  border-radius: 5px;
}

/****************** 商家信息部分 ******************/
.wrapper .business-info {
  width: 100%;
  height: 20vw;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.wrapper .business-info h1 {
  font-size: 5vw;
}

.wrapper .business-info p {
  font-size: 3vw;
  color: #666;
  margin-top: 1vw;
}

/****************** 评论部分 ******************/
.wrapper .remark {
  display: flex;
  align-items: center;
  margin: 1vw 0 5vw 3vw;
}

.wrapper .remark button {
  background-color: #0084ff;
  color: #fff;
  border: none;
  border-radius: 4px;
  padding: 10px 20px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.wrapper .remark button:hover {
  background-color: #005cbf;
}

/****************** 食品列表部分 ******************/
.wrapper .food {
  width: 100%;
  margin-bottom: 14vw;
}

.wrapper .food li {
  width: 100%;
  box-sizing: border-box;
  padding: 2.5vw;
  user-select: none;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.wrapper .food li .food-left {
  display: flex;
  align-items: center;
}

.wrapper .food li .food-left img {
  width: 20vw;
  height: 20vw;
}

.wrapper .food li .food-left .food-left-info {
  margin-left: 3vw;
}

.wrapper .food li .food-left .food-left-info h3 {
  font-size: 3.8vw;
  color: #555;
}

.wrapper .food li .food-left .food-left-info p {
  font-size: 3vw;
  color: #888;
  margin-top: 2vw;
}

.wrapper .food li .food-right {
  width: 16vw;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.wrapper .food li .food-right .fa-minus-circle {
  font-size: 5.5vw;
  color: #999;
  cursor: pointer;
}

.wrapper .food li .food-right p {
  font-size: 3.6vw;
  color: #333;
}

.wrapper .food li .food-right .fa-plus-circle {
  font-size: 5.5vw;
  color: #0097EF;
  cursor: pointer;
}

/****************** 购物车部分 ******************/
.wrapper .cart {
  width: 100%;
  height: 14vw;
  position: fixed;
  left: 0;
  bottom: 0;
  display: flex;
}

.wrapper .cart .cart-left {
  flex: 2;
  background-color: #505051;
  display: flex;
}

.wrapper .cart .cart-left .cart-left-icon {
  width: 16vw;
  height: 16vw;
  box-sizing: border-box;
  border: solid 1.6vw #444;
  border-radius: 8vw;
  background-color: #3190E8;
  font-size: 7vw;
  color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: -4vw;
  margin-left: 3vw;
  position: relative;
  cursor: pointer;
}

.wrapper .cart .cart-left .cart-left-icon-quantity {
  width: 5vw;
  height: 5vw;
  border-radius: 2.5vw;
  background-color: red;
  color: #fff;
  font-size: 3.6vw;
  display: flex;
  justify-content: center;
  align-items: center;
  position: absolute;
  right: -1.5vw;
  top: -1.5vw;
}

.wrapper .cart .cart-left .cart-left-info p:first-child {
  font-size: 4.5vw;
  color: #fff;
  margin-top: 1vw;
}

.wrapper .cart .cart-left .cart-left-info p:last-child {
  font-size: 2.8vw;
  color: #AAA;
}

.wrapper .cart .cart-right {
  flex: 1;
}

.wrapper .cart .cart-right .cart-right-item {
  width: 100%;
  height: 100%;
  background-color: #38CA73;
  color: #fff;
  font-size: 4.5vw;
  font-weight: 700;
  user-select: none;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
}

/****************** 购物车弹窗样式 ******************/
.cart-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 2000;
}

.cart-modal {
  background-color: white;
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
  max-height: 80vh;
  display: flex;
  flex-direction: column;
}

.cart-modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #eee;
}

.cart-modal-header h3 {
  margin: 0;
  font-size: 18px;
}

.cart-modal-header .fa-times {
  font-size: 20px;
  cursor: pointer;
  color: #999;
}

.cart-modal-header .fa-times:hover {
  color: #666;
}

.cart-modal-content {
  flex: 1;
  overflow-y: auto;
  padding: 15px;
}

.empty-cart {
  text-align: center;
  padding: 40px 0;
  color: #999;
}

.cart-items-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.cart-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}

.cart-item-info h4 {
  margin: 0 0 5px 0;
  font-size: 16px;
}

.cart-item-info p {
  margin: 2px 0;
  font-size: 14px;
  color: #666;
}

.cart-item-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.btn-decrease, .btn-increase {
  width: 30px;
  height: 30px;
  border: 1px solid #ddd;
  background: white;
  border-radius: 50%;
  cursor: pointer;
}

.btn-remove {
  background: #ff4757;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 5px 10px;
  cursor: pointer;
}

.quantity {
  min-width: 20px;
  text-align: center;
}

.cart-modal-footer {
  padding: 15px;
  border-top: 1px solid #eee;
}

.cart-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.btn-clear {
  background-color: #ff4757;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 8px 15px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.btn-clear:hover {
  background-color: #ff6b81;
}

.cart-total p {
  margin: 5px 0;
}

.total-amount {
  font-weight: bold;
  font-size: 18px;
  color: #ff6b6b;
}

.btn-checkout {
  width: 100%;
  padding: 12px;
  background: #38CA73;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  margin-top: 10px;
}

.btn-checkout:hover {
  background: #2db863;
}
</style>